module ActiveRecord
  class Base
    VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset,
    :order, :select, :readonly, :group, :from, :include_conditions ]
  end
  
  module Associations
    module ClassMethods
      def select_all_rows(options, join_dependency)
        if options[:include_conditions]
          connection.select_all(
            construct_finder_sql_with_included_and_conditioned_associations(options, join_dependency),
            "#{name} Load Including Conditioned Associations"
          )
        else
          connection.select_all(
            construct_finder_sql_with_included_associations(options, join_dependency),
            "#{name} Load Including Associations"
          )
        end
      end

      def construct_finder_sql_with_included_and_conditioned_associations(options, join_dependency)
        scope = scope(:find)
        sql = "SELECT #{column_aliases(join_dependency)} FROM #{(scope && scope[:from]) || options[:from] || table_name} "
       
        association = join_dependency.join_associations.collect do |join|         
          result = join.association_join
          if include_condition = options[:include_conditions][join.reflection.name.to_s.intern]
            result << %(AND %s.%s ) % [join.aliased_table_name, sanitize_sql(include_condition)]
          end
          result
        end
        sql << association.join
        
        add_joins!(sql, options, scope)
        add_conditions!(sql, options[:conditions], scope)
        add_limited_ids_condition!(sql, options, join_dependency) if !using_limitable_reflections?(join_dependency.reflections) && options[:limit]
        
        sql << "ORDER BY #{options[:order]} " if options[:order]
        
        add_limit!(sql, options, scope) if using_limitable_reflections?(join_dependency.reflections)
        
        return sanitize_sql(sql)
      end
    end  
  end
end